package controller

import (
	"github.com/gin-gonic/gin"
	"main/app/middleware"
	"main/app/model"
	"net/http"
	"time"
)

/**
登录
 */
func Login(c *gin.Context){
	var userInfo model.UserInfo
	if err := c.BindJSON(&userInfo);err!=nil{
		c.JSON(http.StatusOK,gin.H{
			"message":err,
			"token":"",
			"status":200,
		})
		return
	}

	user,err := model.FindUser(&userInfo)

	if err!=nil{
		c.JSON(http.StatusOK,gin.H{
			"message":"账号密码不正确,请重新输入",
			"token":"",
			"status":200,
		})
	}else{
		token,err := createToken(user)
		if err!=nil{
			c.JSON(http.StatusOK,gin.H{
				"message":"token生成失败",
				"token":"",
				"status":200,
			})
		}
		c.JSON(http.StatusOK,gin.H{
			"message":"登录成功",
			"token":token,
			"status":200,
		})
	}
}

/**
注册
 */
func Register(c *gin.Context){
	var user model.User
	if err := c.Bind(&user);err!=nil{
		c.JSON(http.StatusOK,gin.H{
			"message":"出错了",
			"status":200,
		})
		return
	}
	err := model.CreateUser(&user)
	if err!=nil{
		c.JSON(http.StatusOK,gin.H{
			"message":"出错了",
			"status":200,
		})
	}else{
		token,err := createToken(&user)
		if err!=nil{
			c.JSON(http.StatusOK,gin.H{
				"message":"token生成失败",
				"token":"",
				"status":200,
			})
		}
		c.JSON(http.StatusOK,gin.H{
			"message":"注册成功",
			"token":token,
			"status":200,
		})
	}
}

/**
生成token
 */
func createToken(user *model.User)(token string,err error){
	claims := &middleware.JWTClaims{
		UserID : user.Id,
		Username: user.Username,
		Password: user.Password,
		Permission: []string{},
	}
	claims.IssueAt   = time.Now().Unix()
	claims.ExpiresAt = time.Now().Add(time.Second * time.Duration(middleware.ExpireTime)).Unix()

	token,err = middleware.CreateToken(claims)
	if err!=nil{
		return "",err
	}
	return token,nil
}